package dictionary

import (
	"context"
	"wh-1-backend/internal/dao"
	"wh-1-backend/internal/model"
	"wh-1-backend/internal/model/do"
	"wh-1-backend/internal/model/entity"
	"wh-1-backend/internal/service"
)

type sDictionary struct {
}

func New() *sDictionary {
	return &sDictionary{}
}

func init() {
	service.RegisterDictionary(New())
}

func (d *sDictionary) List(ctx context.Context) (res []*entity.Dictionary, err error) {
	err = dao.Dictionary.Ctx(ctx).Scan(&res)
	return
}

func (d *sDictionary) SaveDicType(ctx context.Context, dicType *do.Dictionary) (err error) {
	_, err = dao.Dictionary.Ctx(ctx).Data(dicType).Insert()
	return
}

func (d *sDictionary) DelDicType(ctx context.Context, id uint) (err error) {
	_, err = dao.Dictionary.Ctx(ctx).Where(dao.Dictionary.Columns().Id, id).Delete()
	return
}

func (d *sDictionary) ItemPageList(ctx context.Context, dType string, page int, pageSize int) (total int, list []*entity.DictionaryItem, err error) {
	total, err = dao.DictionaryItem.Ctx(ctx).Where(dao.DictionaryItem.Columns().Type, dType).Count()
	if err != nil {
		return
	}
	if total > 0 {
		err = dao.DictionaryItem.Ctx(ctx).Where(dao.DictionaryItem.Columns().Type, dType).Page(page, pageSize).Scan(&list)
	}
	return
}

func (d *sDictionary) SaveDicItem(ctx context.Context, input model.CreateDicInput) (err error) {
	_, err = dao.DictionaryItem.Ctx(ctx).InsertAndGetId(do.DictionaryItem{
		Code:  input.Code,
		Value: input.Value,
		Type:  input.Type,
	})
	return
}
func (d *sDictionary) UpdateDicItem(ctx context.Context, id uint, input model.CreateDicInput) (err error) {
	_, err = dao.DictionaryItem.Ctx(ctx).Where(dao.DictionaryItem.Columns().Id, id).
		Update(do.DictionaryItem{
			Code:  input.Code,
			Value: input.Value,
		})
	return
}

func (d *sDictionary) DeleteDicItem(ctx context.Context, id uint) (err error) {
	_, err = dao.DictionaryItem.Ctx(ctx).
		Where(dao.DictionaryItem.Columns().Id, id).
		Delete()
	return
}

func (d *sDictionary) ItemList(ctx context.Context, dType string) (list []*entity.DictionaryItem, err error) {
	err = dao.DictionaryItem.Ctx(ctx).Where(dao.DictionaryItem.Columns().Type, dType).Scan(&list)
	return
}
